import pandas as pd
import matplotlib.pyplot as plt
import statistics
import datetime

from lw_config import config_util

# 替换为你的Excel文件路径
file_path = config_util.get_2024_execl()

# 使用pandas的read_excel函数读取文件
all_sheet = pd.read_excel(file_path, sheet_name=None, keep_default_na=False)


def get_w2(w2):
    if w2:
        return w2
    else:
        return 0


# 日期
rq = []
# 体重
weight = []
lines = '日期,平均体重\n'
for sheet_name, sheet_dframe in all_sheet.items():
    # 过滤没有数据的行
    single_df = sheet_dframe.dropna(how="all")

    lines += sheet_name + ":\n"
    for index, row in single_df.iterrows():
        if row['日期']:
            s = []
            if get_w2(row['体重1']) != 0:
                s.append(get_w2(row['体重1']))
            if get_w2(row['体重2']) != 0:
                s.append(get_w2(row['体重2']))
            # print(f'{row["日期"]},{s}')
            if len(s) > 0:
                avg = round(statistics.mean(s), 1)
                if avg != 0:
                    lines += "\t" + str(row['日期']) + ',' + str(avg) + '\n'
                    rq.append(str(row['日期']))  # x字符串没关系
                    weight.append(avg)  # y轴得要数字了，不然高低不好排
                    # print(f'{row["日期"]},{avg}')

plt.figure(figsize=(20, 8), dpi=80)
print(f'x轴数量：{len(rq)}')
# plt.plot(rq, weight, color='lime', linestyle='-.') # 自定义线颜色和格式
plt.plot(rq, weight, markerfacecolor='red')  # 默认颜色个格式
# plt.plot(rq, weight, 'r-.')  # 红色+点线格式
for a, b in zip(rq, weight):
    plt.text(a, b, str(b))
plt.title('2024_weight_changes')
# plt.xticks(rq[::5], rotation=90)
plt.xticks(rotation=90)
# plt.xlabel('date')
# plt.ylabel('avg-weight')
plt.tight_layout()

# 获取当前日期时间
now = datetime.datetime.now()
# 格式化日期时间为字符串
date_str = now.strftime("%Y%m%d_%H%M")

# plt.show()
plt.savefig(f'2024_weight_lost{date_str}.png')
plt.close()  # 需要清空后再生成

# with open("./plot.txt", 'w', encoding='UTF-8') as file:
#     file.write(lines)
